import { createRouter, createWebHashHistory } from 'vue-router'

import Layout from '@/views/Layout'
import Home from '@/views/Home/index.vue'
import store from '@/store'
// 按需加载
const Category = () => import('@/views/category/index.vue')
const SubCategory = () => import('@/views/category/sub.vue')
const Product = () => import('@/views/goods/index.vue')
const Login = () => import('@/views/login/index.vue')
const LoginCallback = () => import('@/views/login/components/callback.vue')
const Cart = () => import('@/views/cart/index.vue')
const PayCheckout = () => import('@/views/member/pay/checkout')
const PayIndex = () => import('@/views/member/pay/index')
const PayCallback = () => import('@/views/member/pay/callback')
const routes = [
  // 登录
  {
    path: '/login',
    component: Login
  },
  // qq登录
  {
    path: '/login/callback',
    component: LoginCallback
  },
  {
    // 首页布局容器
    path: '/',
    component: Layout,
    children: [
      {
        // 首页
        path: '/',
        component: Home
      },
      {
        // 一级菜单
        path: '/category/:id',
        component: Category
      },
      {
        // 二级菜单
        path: '/category/sub/:id',
        component: SubCategory
      },
      {
        // 商品详情
        path: '/product/:id',
        component: Product
      },
      {
        // 购物车
        path: '/cart',
        component: Cart
      },
      {
        // 结算
        path: '/member/checkout',
        component: PayCheckout
      },
      {
        // 支付
        path: '/member/pay',
        component: PayIndex
      },
      {
        // 支付完成
        path: '/pay/callback',
        component: PayCallback
      }
    ]
  }
]

const router = createRouter({
  history: createWebHashHistory(),
  routes,
  scrollBehavior () {
    return { top: 0 }
  }
})

// 导航守卫
router.beforeEach((to, from, next) => {
  // 获取token
  const token = store.state.user.profile.token
  // 判断是否以/member开头并且是否登录
  if (to.path.startsWith('/member') && !token) {
    next(`/login?redirectUrl=${to.fullPath}`)
  }
  next()
})

export default router
